const url = require('url');
const querystring = require('querystring');
const config = require('config');
const co = require('co');
const Session = require('../util/session');
const auth = require('../util/auth');
const logger = require('flogger').getLogger();
const UserService = require('../services/user-services');

module.exports = function (req, res, next) {
  // 已登陆，放行
  let currentUserId = Session.getCurrentUserId(req);

  // /webim/pages/** 为强制cas
  if (currentUserId && !/^\/webim\/pages\//.test(req.originalUrl)) {
    return next();
  }

  let fullUrl = `${req.protocol}://${req.get('host') + req.originalUrl}`;

  let newUrl = url.parse(fullUrl);
  newUrl.search = undefined;
  newUrl.query = querystring.parse(newUrl.query);

  let ticket = req.query.ticket;

  // 重定向刷ticket
  if (!ticket) {
    let service = url.format(newUrl);
    res.redirect(`${config.ORIGINAL}/accounts?service=${encodeURIComponent(service)}`);
    return;
  }

  delete newUrl.query.ticket;

  co(function*() {
    let authInfo = yield auth.casLogin(url.format(newUrl), ticket);
    let user = yield UserService.findOrRegister(authInfo.uid);

    logger.info(`CAS 登录成功, ${user.nickname} 的授权信息为`, authInfo);
    res.clearCookie(config.AUTH_COOKIE_NAME);
    Session.setAuthCookie(res, user.id);
    req.current_user_id = user.id;
    next();
  }).catch(err => {
    // 允许刷新
    if (err === 'no' && currentUserId) {
      next();
    } else {
      next(err);
    }
  });
};
